import { useEffect } from 'react'
import { useRequest } from 'ahooks'

import { useControllerRef } from '@/hooks/useAbortController'
import { useRequestSyncStorePlugin } from '@/hooks/useRequestSyncStorePlugin'
import { apiGetWaybillDetail } from './apis'
import { IWaybillDetailRes } from './interface'
import { useBoundStore } from './store'
import { useUrlParams } from './utils'

export const useDetail = () => {
  const { waybillNo } = useUrlParams()

  const controllerRef = useControllerRef()
  const requestSyncStorePlugin = useRequestSyncStorePlugin({
    onMaybeChange: request =>
      useBoundStore.setState({
        detail: request.data,
      }),
  })

  const request = useRequest<IWaybillDetailRes, []>(
    () => {
      controllerRef.current.abort()
      controllerRef.current = new AbortController()
      return apiGetWaybillDetail({ waybillNo }, controllerRef.current.signal)
    },
    {},
    [requestSyncStorePlugin],
  )

  // 将 useRequest 的结果对象挂载到 store，供外部通过 store.getDetail() 触发 run
  useEffect(() => {
    useBoundStore.setState({ request })
  }, [request])
}
